package com.esun.payment_api.security.filter;

import com.esun.common.utils.JWTUtils;
import com.esun.common.utils.StringUtils;
import com.esun.payment_api.security.model.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * token过滤器 用于在Token解析成功时设置上下文授权信息
 * 注: 此处不做token错误信息返回
 *
 * @author yzd
 */
@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        System.out.println("JwtAuthTokenFilter doFilterInternal");
        HashMap<String, Object> map = new HashMap<>();
        try {
            String token = JWTUtils.getToken(request);
            System.out.println("token：" + token);
            if(StringUtils.isNotNull(token)&&JWTUtils.getAuthentication() == null) {
                LoginUser loginUser = JWTUtils.getLoginUser(request);
                if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(JWTUtils.getAuthentication())) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        chain.doFilter(request, response);

    }
}
